package com.lmk.org.service.Impl;

import com.lmk.basic.service.Impl.BaseServiceImpl;
import com.lmk.org.domain.Department;
import com.lmk.org.mapper.DepartmentMapper;
import com.lmk.org.service.DepartmentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
   @Resource
    private DepartmentMapper mapper;
    /*
    @Override
    @Transactional
    public void add(Department department) {
        mapper.save(department);
    }

    @Override
    @Transactional
    public void del(Long id) {
        mapper.remove(id);
    }

    @Override
    @Transactional
    public void update(Department department) {
        mapper.update(department);
    }

    @Override
    public Department findById(Long id) {
        return mapper.loadById(id);
    }

    @Override
    public List<Department> findAll() {
        return mapper.loadAll();
    }

    @Override
    public PageList<Department> queryPage(BaseQuery query) {
        // 查询总条数
        Long count = mapper.queryCount(query);

        if (count < 1) {
            return new PageList<Department>();
        }
        // 进行分页查询
        List<Department> list = mapper.queryDate(query);
        return new PageList<Department>(count, list);
    }

    @Override
    public void batchdel(List<Long> ids) {
        mapper.batchdel(ids);
    }*/

    @Override
    public List<Department> findDeptTree() {
        // 查询所有Department对象
        List<Department> list = mapper.loadAll();
        // 定义一个map集合
        HashMap<Long, Department> map = new HashMap<>();
        for (Department department : list) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        for (Department department : list) {
            if(department.getParent_id() == null) {//顶级部门
                deptTree.add(department);
            }else{
                Long parent_id = department.getParent_id();
                Department parentdepartment = map.get(parent_id);
                parentdepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
